/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package gridworld_v5;

import java.util.LinkedList;
import java.util.List;
import java.util.Random;

/**
 *
 * @author Jonah
 */
public class ThreadedBug extends ThreadedActor {
    /*implementation comment*/
    ////<editor-fold defaultstate="collapsed" desc="Static Variables">
    //</editor-fold>
    ////<editor-fold defaultstate="collapsed" desc="Instanced Variables">
    private List<Tile> safeTiles = new LinkedList();
    //</editor-fold>
    ////<editor-fold defaultstate="collapsed" desc="Constructor">
    public ThreadedBug(Game game, Board board, Tile tile) {
        super(game, board, tile);
        super.actorType = PossibleStates.Bug;
        
    }
    //</editor-fold>
    ////<editor-fold defaultstate="collapsed" desc="Class Methods">
    //</editor-fold>
    ////<editor-fold defaultstate="collapsed" desc="Abstract Override Methods">
   @Override
    public void checkSafeTiles() {
        List<Tile> unsafeTiles = new LinkedList();
        List<Tile> buggyTiles = new LinkedList();
        safeTiles.clear();
        safeTiles.addAll(currentTile.getNeighbors());
        for (Tile t: safeTiles){
            if ( 
                (t.getTileState().equals(PossibleStates.Bug)) ||
                (t.getTileState().equals(PossibleStates.Bug_Rock)) ||
                (t.getTileState().equals(PossibleStates.Bug_Flower))
            ){
                unsafeTiles.add(t);
            }
            if (t.getTileState().equals(PossibleStates.Critter)){
                unsafeTiles.add(t);
                buggyTiles.addAll(t.getNeighbors());
            }
        }
        safeTiles.removeAll(unsafeTiles);
        if ((safeTiles.size()<1)&&(buggyTiles.size()>0)){
            safeTiles = buggyTiles;
        }else if (safeTiles.size()<1){
            safeTiles.add(currentTile);
        }
    }
    @Override
    public void run() {
        
        int index;
        while (!dead){
                //System.out.println("run():" + this);
                checkSafeTiles();
                index = (int) (Math.random()*safeTiles.size());
                System.out.println(
                          "Bug" + this + " has moved to tile:" 
                        + (safeTiles.get( index ).getIndex()) 
                        + " : has lived " + lifeSpanPassed() + " mili seconds"
                        );
                moveToTile( safeTiles.get( index ) );
                try {
                    //System.out.println("sleep time:" + game.gv.InitialTurnTime);
                    Thread.sleep( 
                            (long) (game.getActorDirector().getTimeInterval(actorType))
                            );

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
        }

    }
    //</editor-fold>
}
